from pathlib import Path

#
import pandas as pd

#
from common import *


def _get_detail_platform(indexed_plaform: str):
    return "-".join(indexed_plaform.split("-")[1:]) if "-" in indexed_plaform else ""


def _get_release_type(indexed_release_type: str):
    if "-" not in indexed_release_type:
        return "linkto"
    splitted = indexed_release_type.split("-")[1:]
    if "网盘" in splitted[0]:
        result = splitted[1]
    elif splitted[0] == "None":
        result = "linkto"
    elif splitted[0] == "Github":
        result = "github"
    elif splitted[0] == "Gitee":
        result = "gitee"
    elif splitted[0] == "大学镜像站":
        result = "mirrorFTP"
    else:
        result = "download"
    return result


# ============
def load_records(excel_path: Path, sheet_name: str) -> pd.DataFrame:
    df = _get_df_from_table_file(excel_path, sheet_name)
    df = _purify_df(df)
    return df


def _get_df_from_table_file(excel_path: Path, sheet_name: str) -> pd.DataFrame:
    """
    如果用多个csv存数据，那么csv文件的名称为{sheet_name}.csv
    """
    LOGGER.info("已读取手动配置的excel数据")
    df = pd.read_excel(excel_path, sheet_name=sheet_name, header=0)
    df = df.fillna("").sort_values(["key", "name", "releaseUrl", "platform"])
    return df


def _purify_df(df: pd.DataFrame) -> pd.DataFrame:
    df = df[~df["hidden"]]
    df["releaseType"] = df["releaseType"].map(_get_release_type)
    df["platform"] = df["platform"].map(_get_detail_platform)
    return df
